package com.liveinstars.activity.application.service;

import com.liveinstars.activity.application.assembler.ActivityAssembler;
import com.liveinstars.activity.business.activity.entity.ActivityDO;
import com.liveinstars.activity.business.activity.enums.ActivityTypeEnum;
import com.liveinstars.activity.business.activity.repository.po.ActivityMembers;
import com.liveinstars.activity.business.activity.service.ActivityService;
import com.liveinstars.activity.business.activity.service.QuestionService;
import com.liveinstars.activity.business.activity.service.impl.ActivityExceptionEnum;
import com.liveinstars.api.dto.*;
import com.liveinstars.api.facade.ImUserCentreApi;
import com.liveinstars.api.im.BadWordRecognizeService;
import com.liveinstars.api.im.ChatGroupApi;
import com.liveinstars.api.im.ChatGroupApiService;
import com.liveinstars.api.im.TodoApi;
import com.liveinstars.api.im.vo.ChatGroupRecordVO;
import com.liveinstars.api.im.vo.NoticeMessageVO;
import com.liveinstars.api.im.vo.TodoVO;
import com.liveinstars.api.im.vo.WordBadLevel;
import com.liveinstars.api.post.facade.IPostsApi;
import com.liveinstars.api.query.ActivityNewQuery;
import com.onepiece.shipelves.common.Result;
import com.onepiece.shipelves.common.exception.QuHuiRuntimeException;
import com.onepiece.shipelves.common.utils.ServiceUtils;
import com.onepiece.shipelves.common.vo.Page;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 多个service协同工作的地方
 * 如拼装一个dto，从各个微服务把数据集中起来，返回给endpoint
 */
@Service
public class ActivityApplicationService {
    private static final Logger logger = LoggerFactory.getLogger(ActivityApplicationService.class);

    @Autowired
    ActivityService activityService;

    @Autowired
    QuestionService questionService;

    @Autowired
    ChatGroupApi chatGroupApi;

    @Autowired
    ChatGroupApiService chatGroupApiService;

    @Autowired
    ImUserCentreApi imUserCentreApi;

    @Autowired
    TodoApi todoApi;

    @Autowired
    IPostsApi postsApi;

    @Autowired
    BadWordRecognizeService badWordRecognizeService;


    public ActivityDO getDetailById(Integer id) {
        return activityService.getDetailById(id);
    }

    public ActivityDO updateActivityById(ActivityDO activityDO, Integer activityId) {
        return activityService.updateById(activityDO, activityId);
    }

    public List<QuestionDto> getQuestions(Integer activityId) {
        return questionService.getQuestions(activityId);
    }

    public Page<ActivityDto> pageByQuery(ActivityNewQuery query) {

        Page<ActivityDO> pageDos = activityService.pageByQuery(query);

        Page<ActivityDto> page = new Page<ActivityDto>(ActivityAssembler.toDTOS(pageDos.getList()),
                pageDos.getPageNum(),
                pageDos.getPageSize(),
                pageDos.getTotalCount()
        );
        return page;
    }

    public Page<ActivityDO> pageByNewQuery(ActivityNewQuery query, Integer uid) {
        return activityService.pageByNewQuery(query, uid);
    }

    public List<ActivityDto> getActivitys(Integer userId) {
        return activityService.getActivitys(userId);
    }

    public ActivityDO createActivity(ActivityDO activityDO) {

        //如果活动的内容没有违法词汇，则直接审核通过
        Map<String, String> map = new HashMap<>();
        map.put("content", activityDO.getAim());
        WordBadLevel aimWordBadLevel = badWordRecognizeService.getWordBadLevel(map);
        map.clear();
        map.put("content", activityDO.getDescription());
        WordBadLevel descWordBadLevel = badWordRecognizeService.getWordBadLevel(map);
//        logger.info("before save activity {} {}", aimWordBadLevel, descWordBadLevel);
        if(aimWordBadLevel.getScore() + descWordBadLevel.getScore() == 0){
            activityDO.setStatus(1);
        }
//        logger.info("before save activity {}", activityDO);
        activityDO = activityService.createActivity(activityDO);

        if (activityDO != null) {
            logger.debug("save activity success");
            //新建的如果是招募活动，要给该用户新建一个小圈，需要判断用户在该兴趣下有没有小圈，有则不新建
            if (activityDO.getType().equals(ActivityTypeEnum.EMPLOY.getValue())) {
                logger.debug("save activity is employ");
                Result<List<ChatGroupRecordVO>> listResult = chatGroupApi.listChatGroupByCreateUserIdAndInterestId(Long.valueOf(activityDO.getUserId()), activityDO.getGroupId());
                logger.debug("save activity listresult size {}", listResult.getData().size());
                if (listResult.getData().size() == 0) {
                    Result<ChatGroupRecordVO> chatGroup = chatGroupApiService.createChatGroup(activityDO.getAim(), Long.valueOf(activityDO.getUserId()), "", activityDO.getDescription(),
                            1, 0, "", activityDO.getGroupId());
                } else {
                    logger.debug("activity group is already exist");
                }
            }else if(activityDO.getType().equals(ActivityTypeEnum.INTEREST.getValue())){
                //兴趣活动如果审核通过，则给圈子里面的人发通知消息
                logger.debug("save activity is interest");
                NoticeMessageVO messageVO = new NoticeMessageVO();
                messageVO.setUserId(Long.valueOf(activityDO.getUserId()));
                messageVO.setChatGroupId(Long.valueOf(activityDO.getSmallGroupId()));
                Result<GetUserInfo> userInfoResult = imUserCentreApi.getUserInfo(activityDO.getUserId());
                GetUserInfo userInfo = userInfoResult.getData();
                if(userInfo != null){
                    messageVO.setContent(userInfo.getNickName() + "发布了" + activityDO.getAim() +"活动, 快去围观吧" );
                    messageVO.setToId(0L);
                    chatGroupApiService.sendMessage(messageVO);
                }
            }


            return activityDO;
        }


        return null;
    }

    public List<ActivityMemberDto> getJoinMembers(Integer id) {
        List<ActivityMembers> joinMembers = activityService.getJoinMembers(id);

        List<Integer> userIds = ServiceUtils.fetchPropertyList(joinMembers, ActivityMembers::getUserId);

        Map<Integer, GetUserInfo> userInfoMap = getGetUserInfoMap(userIds);
        return joinMembers.stream().map((m) -> {
                    ActivityMemberDto memberDto = ActivityAssembler.toDTO(m);
                    GetUserInfo getUserInfo = userInfoMap.get(m.getUserId());
                    if (getUserInfo != null) {
                        memberDto.setUserName(getUserInfo.getUserName());
                        memberDto.setUserLogo(getUserInfo.getLogo());
                    }
                    return memberDto;
                }

        ).collect(Collectors.toList());

    }

    private Map<Integer, GetUserInfo> getGetUserInfoMap(List<Integer> userIds) {
        Map<Integer, GetUserInfo> userInfoMap = new HashMap<>();
        BatchGetUserReq batchGetUserReq = new BatchGetUserReq();
        batchGetUserReq.setUids(userIds);
        Result<List<GetUserInfo>> userInfoListResult = imUserCentreApi.batchGetUserInfo(batchGetUserReq);
        if (userInfoListResult.getCode().equals(Result.SUCCESS)) {
            List<GetUserInfo> userInfoList = userInfoListResult.getData();
            userInfoMap = ServiceUtils.convertToMap(userInfoList, GetUserInfo::getUid);
        } else {
            throw new RuntimeException(userInfoListResult.getMessage());
        }
        return userInfoMap;
    }

    public Boolean joinActivity(Integer activityId, Integer userId, String reqMsg) {

        Result<Boolean> result = new Result<>();
        String message = "";
        boolean success = true;
        Result<GetUserInfo> userInfoResult = imUserCentreApi.getUserInfo(userId);
        GetUserInfo userInfo = userInfoResult.getData();
//        logger.info("userinfo is {}", userInfo);

        if (userInfo == null || userInfo.getUid() < 1) {
            throw new QuHuiRuntimeException(ActivityExceptionEnum.USER_IS_NOT_EXIST);
        }
        ActivityDO activity = activityService.getDetailById(activityId);
        if (activity == null || activity.getId() < 1) {
            throw new QuHuiRuntimeException(ActivityExceptionEnum.ACTIVITY_IS_NOT_EXIST);
        }
        if (activity.getUserId().equals(userId)) {
            throw new QuHuiRuntimeException(ActivityExceptionEnum.ACTIVITY_OWNER_CANT_JOIN);
        }


        int limitPeople = activity.getLimitPeople();
        if (limitPeople != 0) {
            int count = activityService.countByActivityId(activityId);
            if (count >= limitPeople) {

                throw new QuHuiRuntimeException(ActivityExceptionEnum.ACTIVITY_JOIN_LIMIT);
            }
        }


        if (activity.getNeedcheck() == 1) {

            ActivityMembers member = activityService.getActivityMemberByActivityIdAndUserId(activityId, userId);

            if (member != null) {
                throw new QuHuiRuntimeException(ActivityExceptionEnum.ACTIVITY_JOIN_USER_IS_EXIST);
            }

            if (activity.getType().equals(ActivityTypeEnum.EMPLOY.getValue())) {
                logger.info("getChatGroupByCreateUserIdAndInterestId  {} {}", activity.getUserId(), activity.getGroupId());
                ChatGroupRecordVO chatGroupRecordVO = chatGroupApi.getChatGroupByCreateUserIdAndInterestId(Long.valueOf(activity.getUserId()), activity.getGroupId());

                if (chatGroupRecordVO != null) {
                    logger.info("joinactivity   {} ", chatGroupRecordVO.toString());
                    //调用远程服务添加代办事项
                    TodoVO todoVO = todoApi.addTodo((long) userId, (long) activity.getUserId(), 2, activityId, (long) Math.toIntExact(chatGroupRecordVO.getId()), reqMsg);

                } else {
                    throw new QuHuiRuntimeException((ActivityExceptionEnum.ACTIVITY_JOIN_USER_NO_GROUP));
                }

            } else if (activity.getType().equals(ActivityTypeEnum.INTEREST.getValue())) {
                //如果是兴趣活动，则groupid为0
                TodoVO todoVO = todoApi.addTodo((long) userId, (long) activity.getUserId(), 4, activityId, 0L, reqMsg);

            }
        } else {
            boolean isSuccess = activityService.addActivityMember(activityId, userId);

            if (activity.getType().equals(ActivityTypeEnum.EMPLOY.getValue())) {
                ChatGroupRecordVO chatGroupRecordVO = chatGroupApi.getChatGroupByCreateUserIdAndInterestId(Long.valueOf(activity.getUserId()), activity.getGroupId());
                if (chatGroupRecordVO != null) {
                    isSuccess = chatGroupApi.addChatGroupMember((long) userId, chatGroupRecordVO.getId());
                }
            }
        }

        return true;
    }

    public Boolean addActivityMember(Integer fromId, Integer userId, Integer groupId) {
        boolean b = activityService.addActivityMember(groupId, fromId);
        return b;
    }

    public Boolean getIsApply(Integer userId, Integer id) {
        Boolean has = todoApi.hasJoinTodo(Long.valueOf(userId), id);
        return has;
    }

    public List<ActivityDO> getApplyActivity(Integer userId) {
        List<TodoVO> todoVOS = todoApi.listActivityTodo(Long.valueOf(userId), 0);
        List<Integer> ids = ServiceUtils.fetchPropertyList(todoVOS, TodoVO::getActivityId);
        if (ids.size() > 0) {
            List<ActivityDO> activities = activityService.ListActivityByIds(ids);
            return activities;
        }

        return Collections.emptyList();
    }

    public Boolean viewActivity(Integer id) {
        return activityService.viewActivity(id);
    }

    public Boolean likeActivity(Integer activityId, Integer userId, boolean b) {
        if (b) {
            postsApi.like(activityId, userId);
        } else {
            postsApi.unLike(activityId, userId);
        }
        return activityService.likeActivity(activityId, b);
    }

    public Page<ActivityDO> getAllActivitys(ActivityNewQuery query) {
        return activityService.getAllActivitys(query);
    }

    public Boolean updateStatus(Integer activityId, int status) {
        return activityService.updateStatus(activityId, status);
    }

    public Boolean getIsLike(Integer userId, Integer id) {
//        logger.info("getislike {} {}", userId, id);
        return postsApi.isLike(id, userId);
    }

    public Page<ActivityDO> getGroupActivitys(ActivityNewQuery query) {
        return activityService.getGroupActivitys(query);
    }
}
